<template>
	<view class="page">
		<view class="head">
			<view class="head1">
				<text class="iconfont icon-fenxiang1" @click="goBack"></text>
				<text class="nav-title">店铺管理</text>

			</view>
		</view>
		<view class="main">
			<!-- 菜单导航 -->
			<view class="menu-nav">
				<view class="nav" ref="nav" :style="navList.length <= 3 ? 'flex-direction: row' : ''">
					<view class="list" v-for="(item, index) in navList" :key="item.id" @click="onTab(item)"
						:class="{'active': selectedItem && selectedItem.id === item.id}">
						<text>{{ item.name }}</text>
					</view>
				</view>
			</view>
			<!-- 经营数据 -->
			<view v-if="selectedTab === 'operationalData'" class="operationalData">
				<scroll-view class="bill-container" scroll-y>
				<!--  通知-->
				<view class="notice">
					<view class="left">
						另品网，帮商家赚钱，帮百姓返现，快来加入吧！
					</view>
					<view class="right" @click="look">
						<text>查看</text>
						<text class="iconfont icon-more" @click="more"></text>
					</view>
				</view>
				<!-- <view class="title">
					本月经营数据统计分析表
				</view> -->
				<view class="chart-card">
					<view class="chart-title title">
						本月经营数据统计分析表
					</view>
					<view class="charts-box">
						<canvas canvas-id="monthChart" id="monthChart" class="charts"></canvas>
						<view class="date-picker" >
							
							<text class="expense">金额/元</text> 
							   <picker mode="selector" :range="months" :value="selectedMonth"
								  @change="onDateChange">
								  <view>   
									<text class="txt">{{months[selectedMonth]}}</text>
								 </view>
								</picker>
							</view>
					</view>
				</view>
				
				
				<view class="chart-card">
					<view class="chart-title title">
						本年经营数据统计分析表
					</view>
					<view class="charts-box">
						<canvas canvas-id="yearsdata" id="yearsdata" class="charts"></canvas>
						<view class="date-picker" >
							
							<text class="expense">金额/元</text> 
							   <picker :range="years" :value="selectedYear" bindchange="onYearChange">
								  <view>   
									<text class="txt">{{years[selectedYear]}}</text>
								 </view>
								</picker>
							</view>
					</view>
				</view>
				
				
				<view class="chart-card">
					<view class="chart-title title">
						历史经营数据统计分析表
					</view>
					<view class="charts-box">
						<canvas canvas-id="histrydata" id="histrydata" class="charts"></canvas>
						<view class="date-picker" >
							
							<text class="expense">金额/元</text> 
							   <picker :range="years" :value="selectedYear" bindchange="onYearChange">
								  <view>   
									<text class="txt">{{years[selectedYear]}}</text>
								 </view>
								</picker>
							</view>
					</view>
				</view>

				</scroll-view>
				<!-- <view class="title">
					本年经营数据统计分析表
				</view> -->
				
			</view>
			<!-- 订单管理 -->
			<view v-if="selectedTab === 'totalManagement'" class="totalManagement">
				<view class="search" @click="onSearch">
					<view class="icon">
						<text class="iconfont icon-sousuo"></text>
					</view>
					<view class="hint">
						<text class="max"></text>

					</view>
				</view>
				<view class="select">
					<view class="date">
						<u-datetime-picker ref="datetimePicker" :show="show" v-model="value1" mode="date"
							:formatter="formatter" @confirm="confirm" @cancel="cancel"></u-datetime-picker>
						<view class="date1" @click="show=true">
							<text>2025-08-16</text>
							<text class="iconfont icon-xiala1"></text>
						</view>
					</view>
					<view class="money">
						<view class="title">
							共计<text>111</text>单
						</view>
						<view class="title1">
							|
						</view>
						<view class="title">
							合计金额：<text>5569</text>元
						</view>
						
					</view>
				</view>
				<view class="detail" v-for="(item,index) in storeList" :key="index">
					<view class="left">
						<image :src="item.logo" mode=""></image>
					</view>
					<view class="right">
						<view class="top">
							<view class="title">
								{{item.name}} (150xxxx0123)
							</view>
							<view class="state">
								已完成
							</view>
						</view>
						<view class="bottom">
							<view class="title">
								<view class="price">
									收款：+￥12
								</view>
								<view class="">
									积分：+<text>25</text>
								</view>
							</view>
							<view class="date">
								2024-12-26
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 商品管理 -->
			<view v-if="selectedTab === 'merchandiseManagement'" class="merchandiseManagement">
				<view class="search" @click="onSearch">
					<view class="icon">
						<text class="iconfont icon-sousuo"></text>
					</view>
					<view class="hint">
						<text class="max"></text>

					</view>
				</view>
				<view class="select">
					<view class="tab">
						<view class="nav" ref="nav" :style="tabList.length <= 5 ? 'flex-direction: row' : ''">
							<view class="list" v-for="(item, index) in tabList" :key="item.id" @click="onTab1(item)"
								:class="{'active': selected && selected.id === item.id}">
								<text>{{ item.name }}</text>
								<text>{{ storeList1.length }}</text>
							</view>
						</view>
					</view>

				</view>
				<view class="operate">
					<view class="select">
						<view>最新创建在上</view>
						<text class="iconfont icon-xiala1"></text>
					</view>
					<view class="edit" @click="isEdit = !isEdit">
						<view class="edit1">
							<text v-if="isEdit" class="iconfont icon-caozuo"></text>
							<view>{{isEdit?'取消批量':'批量操作'}}</view>
						</view>
					</view>

				</view>

				<view v-if="storeList1 && storeList1.length > 0" class="detail" v-for="(item, index) in storeList1" :key="index">
					<view class="check" @click="toggleCheck(index)" v-if="isEdit">
						<text class="iconfont" :class="item.isChecked ? 'icon-checked' : 'icon-check'"></text>
					</view>
					<view class="left">
						<image :src="item.logo" mode=""></image>
					</view>
					<view class="right">
						<view class="top">
							<view class="title">
								{{item.name}}
							</view>
							<view class="details">
								<view class="price">
									现价￥<text>180.0</text>
								</view>
								<view class="integral">
									+20积分
								</view>
							</view>
						</view>
						<view class="bottom1">
							<view class="date">
								上传时间：2025-01-14
							</view>
							<view class="edit">
								<view class="edit1" @click="change">
									修改
								</view>
								<view class="up" @click="edit(item)" v-if="item.edit">
									上架
								</view>
								<view class="up" @click="edit(item)" v-else>
									下架
								</view>
							</view>

						</view>
					</view>
				</view>

				<!-- 合计 -->
				<view class="total" @click="toggleSelectAll" v-if="isEdit">
					<text class="iconfont" :class="selectAll ? 'icon-checked' : 'icon-check'"></text>
					<view class="total1">{{ selectAll ? '取消全选' : '全选' }}</view>
					<view>
						已选
						<text>{{ selectedCount }}</text>
						件商品
					</view>
				</view>

				<view class="bottom">
					<view class="left">

					</view>
					<view class="right">
						<view class="upStore1" v-if="isEdit"  @click="downTotal">
							批量下架
						</view>
						<view class="upStore1" v-if="isEdit" @click="delteTotal">
							批量删除
						</view>
						<view class="upStore" v-else  @click="listProduct">
							发 布 商 品
						</view>
						
						
						
						
					</view>

				</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		components: {

		},
		data() {
			return {
				monthData: [5800, 1800, 2400, 900, 4200, 3500, 2800, 2400, 1800, 2500,1800, 2500],
				
				yearData: [5500, 1800, 2400, 900, 4200, 3500, 2800, 2400, 1800, 2500, 1800, 2500],

				historyData: [5500, 1800, 2400, 900, 4200, 3500, 2800, 2400, 1800, 2500, 1800, 2500],
				
				months: ['01月', '02月', '03月', '04月', '05月', '06月', '07月', '08月', '09月', '10月', '11月', '12月'],
				selectedMonth: 0, // 默认选择 1 月
				years: [], // 存储动态生成的年份列表
				selectedYear: 0 ,// 默认选择当前年份
					
					
				
				isEdit: false, // 编辑模式状态
				selectAll: false, // 全选状态
				// items: Array(20).fill({}).map(() => ({
				// 	isChecked: false
				// })), // 商品列表，初始化时每个商品都未选中
				show: false,
				value1: Number(new Date()),
				selectedTab: 'operationalData', // 初始显示经营数据
				selectedTab1: 'total', //全部商品
				navList: [{
						id: 1,
						name: '经营数据',
						tabName: 'operationalData'
					},
					{
						id: 2,
						name: '订单管理',
						tabName: 'totalManagement'
					},
					{
						id: 3,
						name: '商品管理',
						tabName: 'merchandiseManagement'
					},
				],
				storeList1: [
				  {
				    logo: 'https://pic.nximg.cn/file/20230914/33760392_161909340127_2.jpg',
				    name: '杭州特色小笼包(赤峰红山区)',
				    isChecked: false,
					edit:false
				  },
				  {
				    logo: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.qRz6NYTvrqn23mjgR1GUkwHaE8?w=257&h=180&c=7&r=0&o=5&pid=1.7',
				    name: '北京老北京炸酱面',
				    isChecked: false,
					edit:false
				  },
				  {
				    logo: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.aJeK_HFXapSh1Q71AW29ngHaE8?w=263&h=180&c=7&r=0&o=5&pid=1.7',
				    name: '烧烤',
				    isChecked: false,
					edit:false
				  },],

				
				storeList: [
				  {
				    logo: 'https://pic.nximg.cn/file/20230914/33760392_161909340127_2.jpg',
				    name: '张三'
				  },
				  {
				    logo: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.qRz6NYTvrqn23mjgR1GUkwHaE8?w=257&h=180&c=7&r=0&o=5&pid=1.7',
				    name: '里斯'
				  },
				  {
				    logo: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.aJeK_HFXapSh1Q71AW29ngHaE8?w=263&h=180&c=7&r=0&o=5&pid=1.7',
				    name: '样儿'
				  },
				  {
				    logo: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.erhPYZ6AJKoXhK3HQ3-8CgHaE8?w=277&h=185&c=7&r=0&o=5&pid=1.7',
				    name: '杨亚'
				  },
				  {
				    logo: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.GmPhy9VPQ_htqErsGSc-ngHaE8?w=220&h=180&c=7&r=0&o=5&pid=1.7',
				    name: '红红'
				  },
				  {
				    logo: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.Cpfbgsjb_Ams72ksnWGIMAHaE8?w=287&h=192&c=7&r=0&o=5&pid=1.7',
				    name: '东东'
				  }
				],
				
				tabList: [{
						id: 1,
						name: '全部商品',
						tabName: 'total',
						number: 20
					},
					{
						id: 2,
						name: '已上架',
						tabName: 'vailable',
						number: 20
					},
					{
						id: 3,
						name: '审核中',
						tabName: 'underReview',
						number: 20
					},
					{
						id: 4,
						name: '被驳回',
						tabName: 'rejected',
						number: 20
					},
					{
						id: 5,
						name: '草稿箱',
						tabName: 'draftBox',
						number: 20
					},
				],
				selectedItem: null,
				selected: null,
				deletedItems: [], // 用来存储删除的商品
			}
		},
		mounted() {
			this.selectedItem = this.navList[0];
			this.selected = this.tabList[0]; // 默认选中第一个项
			this.initCanvas();
			this.generateYears();
		},
		computed: {
			formatDate() {
			  if (!this.selectedDate) return ''
			  const date = new Date(this.selectedDate)
			  return `${date.getFullYear()}年${date.getMonth() + 1}月`
			},
			selectedCount() {
				return this.storeList1.filter(item => item.isChecked).length;
			}
		},

		methods: {
        //修改上下架
		edit(item){
			
			item.edit = !item.edit
			console.log(111,item.edit)
		},
			// 日期变化处理
			async onDateChange(e) {
			 this.selectedMonth = e.detail.value;
			},
			// 编辑商品
			change() {
				uni.navigateTo({
					url: '/moduleB/listProduct/listProduct?action=edit'
				});
			},

			// 发布商品
			listProduct() {
				uni.navigateTo({
					url: '/moduleB/listProduct/listProduct?action=list'
				});
			},
			//批量下架
			 downTotal() {
			       this.storeList1.forEach((item) => {
			         if (item.isChecked) {
			           item.edit = true;  // 将选中的商品标记为下架状态
			         }
			       });
			    
			     },
				 
				   // 批量删除
				   delteTotal() {
					      const deletedItems = this.storeList1.filter(item => item.isChecked);
					     
					           // 更新 storeList1，删除已选中的商品
					           this.storeList1 = this.storeList1.filter(item => !item.isChecked);
					     
					           // 将已删除的商品赋值到 deletedItems 数组
					           this.deletedItems = deletedItems;
				   },
			// 切换单个商品的选中状态
			toggleCheck(index) {
				if (this.storeList1 && this.storeList1[index]) {
					this.storeList1[index].isChecked = !this.storeList1[index].isChecked;
					this.checkSelectAllStatus(); // 每次改变选中状态后检查全选状态
				}
			},
			// 切换全选/取消全选状态
			toggleSelectAll() {
				this.selectAll = !this.selectAll;
				this.storeList1.forEach(item => {
					item.isChecked = this.selectAll;
				});
			},
			// 检查全选状态
			checkSelectAllStatus() {
				this.selectAll = this.storeList1.every(item => item.isChecked); // 如果所有项都被选中，则全选为选中
			},


			onSearch() {

			},
			goBack() {
				uni.navigateBack(-1)
			},
			onTab(item) {
				this.selectedItem = item;
				this.selectedTab = item.tabName; // 根据 tabName 切换显示的内容
				if(item.tabName === 'operationalData'){
					this.initCanvas();
				}
			},
			onTab1(item) {

				this.selected = item;
				this.selectedTab1 = item.tabName;
				console.log('item', this.selected)
			},
			//日期
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			//
			cancel() {
				this.show = false
			},
			confirm() {
				this.show = false
			},

			look(){
				uni.navigateTo({
					url:'/moduleA/notice/index'
				})
			},
			
			
			initCanvas(){
				
				this.drawChart('monthChart', this.monthData, '#7AA6FA');
				this.drawChart('yearsdata', this.yearData, '#AEA2F9');
				this.drawChart('histrydata', this.historyData, '#FDC383');
			},
			onYearChange(e) {
				this.selectedYear = e.detail.value; // 获取选择的年份索引
				
			},
			generateYears() {
			    const currentYear = new Date().getFullYear(); // 获取当前年份
			    const startYear = currentYear - 10; // 假设从当前年份的前 10 年开始
			    const endYear = currentYear; // 假设到当前年份的后 10 年为止
			    const years = [];
			
			    for (let year = startYear; year <= endYear; year++) {
			      years.push(year.toString()); // 将年份转为字符串并添加到列表中
			    }
				this.years = years;
				this.selectedYear = years.indexOf(currentYear.toString());
			   
			},
			drawChart(canvasId, data, color) {
				const ctx = uni.createCanvasContext(canvasId, this);
				const width = 380; // canvas宽度
				const height = 200; // canvas高度
				const padding = 30; // 内边距
				const maxValue = 6000; // Y轴最大值
				const barWidth = 15; // 柱宽

				// 清空画布
				ctx.clearRect(0, 0, width, height);

				// 计算柱子之间的间距和总宽度
				const availableWidth = width - 2 * padding;
				const totalBarsWidth = barWidth * data.length;
				const totalGaps = data.length + 1; // 首尾都需要间距
				const spacing = (availableWidth - totalBarsWidth) / totalGaps;

				// 绘制网格线 - 确保网格线覆盖整个图表区域
				ctx.setStrokeStyle('#707070');
				ctx.setLineDash([2, 2]);
				for (let i = 0; i <= 6; i++) {
					const y = padding + (height - 2 * padding) * (1 - i / 6);
					ctx.beginPath();
					ctx.moveTo(padding, y);
					ctx.lineTo(width - padding, y);
					ctx.stroke();
				}

				// 绘制Y轴刻度文字
				ctx.setFontSize(8);
				ctx.setTextAlign('right');
				ctx.setFillStyle('#666666');
				for (let i = 0; i <= 6; i++) {
					const value = (maxValue * i / 6).toFixed(0);
					const y = padding + (height - 2 * padding) * (1 - i / 6);
					ctx.fillText('¥' + value, padding - 5, y + 3);
				}

				// 绘制X轴刻度
				ctx.setTextAlign('center');
				data.forEach((value, index) => {
					const x = padding + spacing * (index + 1) + barWidth * index + barWidth / 2;
					ctx.fillText((index + 1).toString(), x, height - padding + 15);
				});

				// 绘制柱状图
				ctx.setFillStyle(color);
				data.forEach((value, index) => {
					// const x = padding + spacing * (index + 1) + barWidth * index;
					// const barHeight = (height - 2 * padding) * (value / maxValue);
					// const y = height - padding - barHeight;
					// ctx.fillRect(x, y, barWidth, barHeight);
					const x = padding + spacing * (index + 1) + barWidth * index;
					const barHeight = (height - 2 * padding) * (value / maxValue);
					const y = height - padding - barHeight;
					const radius = 4; // 圆角半径
					
					ctx.beginPath();
					// 左下角
					ctx.moveTo(x, y + barHeight);
					// 左边线
					ctx.lineTo(x, y + radius);
					// 左上圆角
					ctx.arc(x + radius, y + radius, radius, Math.PI, -Math.PI/2);
					// 顶部线
					ctx.lineTo(x + barWidth - radius, y);
					// 右上圆角
					ctx.arc(x + barWidth - radius, y + radius, radius, -Math.PI/2, 0);
					// 右边线
					ctx.lineTo(x + barWidth, y + barHeight);
					// 底部线
					ctx.lineTo(x, y + barHeight);
					
					ctx.fill();
				});

				// 执行绘制
				ctx.draw();
			},
			handleMonthChange(e) {
				this.tempMonthIndex = e.detail.value[0]
			},
			handleYearChange(e) {
				this.tempYearIndex = e.detail.value[0]
			},
			confirmMonthPicker() {
				this.monthIndex = this.tempMonthIndex
				this.selectedMonth = this.tempMonthIndex + 1
				this.showMonthPicker = false
				// 模拟获取新数据
				const newData = this.generateRandomData(10)
				this.monthData = newData
				this.drawChart('monthChart', newData, '#8B8BF9')
			},
			confirmYearPicker() {
				this.yearIndex = this.tempYearIndex
				this.selectedYear = this.years[this.tempYearIndex]
				this.showYearPicker = false
				// 模拟获取新数据
				const newData = this.generateRandomData(12)
				this.yearData = newData
				this.drawChart('yearChart', newData, '#8B8BF9')
			},
			handlePopupChange(e) {
				if (!e.show) {
					this.showMonthPicker = false
					this.showYearPicker = false
					this.showHistoryYearPicker = false
				}
			},
			generateRandomData(length) {
				return Array.from({
					length
				}, () => Math.floor(Math.random() * 5000) + 1000)
			},
			showPicker(type) {
				if (type === 'month') {
					this.showMonthPicker = true
					// 使用 nextTick 确保组件已经渲染
					this.$nextTick(() => {
						this.$refs.monthPopup && this.$refs.monthPopup.open()
					})
				} else if (type === 'year') {
					this.showYearPicker = true
					this.$nextTick(() => {
						this.$refs.yearPopup && this.$refs.yearPopup.open()
					})
				} else if (type === 'history') {
					this.showHistoryYearPicker = true
					this.$nextTick(() => {
						this.$refs.historyYearPopup && this.$refs.historyYearPopup.open()
					})
				}
			},
			hidePicker(type) {
				if (type === 'month') {
					this.showMonthPicker = false
					this.$refs.monthPopup && this.$refs.monthPopup.close()
				} else if (type === 'year') {
					this.showYearPicker = false
					this.$refs.yearPopup && this.$refs.yearPopup.close()
				} else if (type === 'history') {
					this.showHistoryYearPicker = false
					this.$refs.historyYearPopup && this.$refs.historyYearPopup.close()
				}
			},
			confirmHistoryYearPicker() {
				this.yearIndex = this.tempYearIndex
				this.selectedHistoryYear = this.years[this.tempYearIndex]
				this.showHistoryYearPicker = false
				// 模拟获取新数据
				const newData = this.generateRandomData(12)
				this.historyData = newData
				this.drawChart('historyChart', newData, '#FFA666')
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "storeManagement.scss";
.page{
		padding-bottom: 0;
		.main .menu-nav .list{
			padding: 26rpx 0;
			text{
				font-size: 28rpx;
			}
		}
	}
	
	.bill-container {
		height: calc(100vh - 280rpx);
		padding-bottom: 20rpx;
	}
	.chart-card {
		
		background-color: #fff;
		border-radius: 8px;

		.chart-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 14px;
			font-weight: 500;
			margin: 0;
			.month-select,
			.year-select {
				display: flex;
				align-items: center;
				font-size: 12px;
				color: #666;
			}
		}
	}
	
	.charts-box {
		position: relative;
	  width: 94%;
	  // overflow: scroll;
	  margin: 0 auto;
	  height: 400rpx;
	  padding: 20rpx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  background: #ffffff;
		border-radius: 6px;
		box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.16); 
		.canvas{
			// width: 1400rpx;  // 320px
			
		}
		.charts {
		  width: 700rpx;  // 320px
		  height: 380rpx; // 200px
		}
		.date-picker{
			position: absolute;
			top:20rpx;
			padding: 0 20rpx;
			left: 0;
			width: 100%;
			display: flex;
			justify-content: space-between;  
			.expense{
				font-size: 18rpx;
				color: #b5b5b5;
			}
			.txt{
				font-size: 18rpx;
				color: #707070;
				position: relative;
				margin-right: 20rpx;
				&::after{
					content: "";
					position: absolute;
					top:6rpx;
					right: -20rpx;
					width: 0;
					height: 0;
					border-left: 8rpx solid transparent; /* 左边透明 */
					border-right: 8rpx solid transparent; /* 右边透明 */
					border-top: 10rpx solid #707070; /* 下边颜色填充为黑色 */
				}
			}
		}
	}
	
	
</style>